<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">厂商名称：</p>
      <el-input
        v-model="listQuery.realName"
        size="small"
        placeholder="请输入厂商名称"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="float:left;margin-top:5px;margin-left:2%">联系电话：</p>
      <el-input
        v-model="listQuery.phoneNumber"
        size="small"
        placeholder="请输入联系电话"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        />
      <el-table-column label="厂商名称" width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="APP显示厂商名称" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.supplierName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银行卡号" width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bankAccount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开户行" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.bankName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="经营商品数" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.runCommodityCount }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"  
        width="200px"
        class-name="small-padding fixed-width"
      > 
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="danger"
            @click="handledelete(row)"
          >
            删除
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-button type="danger" style="float:right" @click="totalDel()">批量删除</el-button>
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="厂家名称：">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="APP显示厂商名称：">
          <el-input v-model="temp.supplierName" />
        </el-form-item>
        <el-form-item label="联系人电话：">
          <el-input v-model="temp.phoneNumber" />
        </el-form-item>
        <el-form-item label="银行卡号：">
          <el-input v-model="temp.bankAccount" />
        </el-form-item>
        <el-form-item label="银行卡开户行：">
          <el-input v-model="temp.bankName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateManu,manufacturerList,delManufacturer,createManufacturer,batchDel } from '@/api/manufacturer'// 异步请求 delLly
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const calendarTypeOptions = [
  { key: 0, display_name: '无效' },
  { key: 1, display_name: '正常' },
  { key: 2, display_name: '锁定' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      deptValue:'',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        phoneNumber:'',
        realName:'',
        sort: '+id'
      },
      deps:[],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '查看详情',
        create: '添加'
      },
      rowId:"",
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      liaUser: null,
      ids:[],
      select:null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
        val.forEach((item)=>{
          this.select=item.id
        })
        this.ids.push(this.select)
    },
    totalDel(){
        this.$confirm('确定删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            var idss=this.ids.join(',')  
            batchDel(idss).then(res=>{
                this.$message({
                type: 'success',
                message: '删除成功!'
                });
             this.getList()
            })  
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        realName:this.listQuery.realName,
        phoneNumber:this.listQuery.phoneNumber
      }
      manufacturerList(params).then(response => {
        this.list = response.content
        console.log(this.list)
        this.total = response.totalElements
        console.log(this.total)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
     handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp)
          updateManu(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createManufacturer(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            setTimeout(function(){  //使用  setTimeout（）方法设定定时1000毫秒
              window.location.reload();//页面刷新
            },1000);
          })
        }
      })
       
    },
    handledelete(row){
        this.rowId=row.id
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            delManufacturer(this.rowId).then(res=>{
                this.$message({
                type: 'success',
                message: '删除成功!'
                });
             this.getList()
            })  
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
       
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>